package com.webSite.demo.cy.downBook;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.filechooser.FileSystemView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HtmlUtil;

public class JsTest {

	public static void main(String[] args) {
		File srcFolder = new File("C:\\Users\\fengzihao\\Desktop\\资源\\txt");
		
		getAllJsFilePaths(srcFolder,"综漫之300英雄⊙怠惰笨淡⊙全本");
	}

	private static String writeSrc = null;
	
	static {
		FileSystemView fsv = FileSystemView.getFileSystemView();
		File com=fsv.getHomeDirectory();    //这便是读取桌面路径的方法了
		writeSrc = com.getPath();
	}
	
	public static void makeBookAndDelete(File srcFolder,String filename) {
		getAllJsFilePaths(srcFolder,filename);
		delIndexAllFile(srcFolder);
		
	}
	
	private static void delIndexAllFile(File srcFolder) {
		File[] fileArray = srcFolder.listFiles();
		for (File file : fileArray) {
			file.delete();
		}
	}
	
	private static void getAllJsFilePaths(File srcFolder,String filename) {
		File[] fileArray = srcFolder.listFiles();
		for (File file : fileArray) {
			if(file.getName().endsWith(".js")) {
				System.out.println(file.getAbsolutePath()+"扫描完成");
				readAndWrite(file.getAbsolutePath(),filename);
			}
		}
	}

	private static void readAndWrite(String absolutePath,String filename) {
		// TODO Auto-generated method stub
		FileReader fileReader = new FileReader(absolutePath,CharsetUtil.CHARSET_GBK);
		//String result = fileReader.readString();
		List<String> resultList = fileReader.readLines();
		List<String> first = new ArrayList<String>();
		for (int i =0;i<resultList.size();i++) {
			if(i==0) {
				first.add(HtmlUtil.cleanHtmlTag(resultList.get(0).replace("document.write(\"", "").replace("\");", "")));
			}else if(i == 2){
				//first.add(HtmlUtil.unwrapHtmlTag(resultList.get(2).replace("document.write ('", "").replace("')", ""),"p"));
				Document doc = Jsoup.parse(resultList.get(2).replace("document.write ('", "").replace("')", ""));
				Element body = doc.body();
				Elements links = body.getElementsByTag("p");
				for (Element element : links) {
					first.add(element.text());
				}
			}
		}
		FileWriter writer = null;
		try {
			writer = new FileWriter(writeSrc+"\\"+filename+".txt");
		}catch(Exception e) {
			System.out.println("没有找到目录");
		}
		writer.appendLines(first);
	}
	
}
